package com.powermall.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.powermall.constant.AuthConstants;
import com.powermall.domain.LoginSysUser;
import com.powermall.mapper.LoginSysUserMapper;
import com.powermall.model.SecurityUser;
import com.powermall.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 商城后台管理系统登录策略的具体实现
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {

    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        // 根据用户名称查询用户对象
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>().
                eq(LoginSysUser::getUsername, username));
        if (!ObjectUtils.isEmpty(loginSysUser)) {
            SecurityUser securityUser = new SecurityUser();
            // 用户存在，查询用户的权限
            Set<String> perms =
                    loginSysUserMapper.selectPermsBySysUserId(loginSysUser.getUserId());
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setUsername(loginSysUser.getUsername());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setStatus(loginSysUser.getStatus());
            // 判断用户是否有权限
            if (!CollectionUtils.isEmpty(perms) && perms.size() != 0) {
                securityUser.setPerms(perms);
            }
            return securityUser;
        }
        return null;
    }
}
